#include "httpmgr.h"

HttpMgr::HttpMgr()
{
    // 连接http请求完成信号
    connect(this, &HttpMgr::sig_http_finish, this, &HttpMgr::slot_http_finish);
}


HttpMgr::~HttpMgr()
{

}

void HttpMgr::PostHttpReq(QUrl url, QJsonObject json, ReqId req_id, Modules mod)
{
    QByteArray data = QJsonDocument(json).toJson();
    // 创建一个HTTP POST请求，并设置请求头和请求体
    // 通过url构造请求
    QNetworkRequest request(url);
    request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
    request.setHeader(QNetworkRequest::ContentLengthHeader, QByteArray::number(data.length()));
    // 发送请求，并处理相应，获取自己的智能指针，构造伪闭包并增加智能指针引用计数
    auto self = shared_from_this();
    QNetworkReply * reply = _manager.post(request, data);
    // 设置信号和槽等待发送完成
    connect(reply, &QNetworkReply::finished, [self, reply, req_id, mod](){
        // 处理错误的情况
        if (reply->error() != QNetworkReply::NoError) {
            qDebug() << "PostHttpReq Error, error msg is: " << reply->errorString();
            // 发送信号通知完成
            emit self->sig_http_finish(req_id, "", ErrorCodes::ERR_NETWORK, mod);
            reply->deleteLater();
            return;
        }

        // 无错误则读取回复
        QString res = reply->readAll();
        // 发送信号通知完成
        emit self->sig_http_finish(req_id, res, ErrorCodes::SUCCESS, mod);
        reply->deleteLater();
        return;
    });
}

void HttpMgr::slot_http_finish(ReqId req_id, QString res, ErrorCodes err, Modules mod)
{
    if (mod == Modules::REGISTERMOD) {
        // 发送信号通知注册模块http响应到来
        emit sig_reg_mod_finish(req_id, res, err);
    } else if (mod == Modules::RESETMOD) {
        // 发送信号通知重置密码模块http响应到来
        emit sig_reset_mod_finish(req_id, res, err);
    } else if (mod == Modules::LOGINMOD) {
        // 发送信号通知重置密码模块http响应到来
        emit sig_login_mod_finish(req_id, res, err);
    }
}

